package com.wsc.wisdomchinaqinghe.activitity.fourmodule;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.Tools.AbPermissionUtils;
import com.wsc.wisdomchinaqinghe.Tools.BitmapUtils;
import com.wsc.wisdomchinaqinghe.Tools.JsonTools;
import com.wsc.wisdomchinaqinghe.Tools.Tools;
import com.wsc.wisdomchinaqinghe.activitity.baseactivity.BaseActivity;
import com.wsc.wisdomchinaqinghe.adapter.PeopleControlTypeAdapter;
import com.wsc.wisdomchinaqinghe.callback.ContributorView;
import com.wsc.wisdomchinaqinghe.constant.Constant;
import com.wsc.wisdomchinaqinghe.javaBean.FeedBackTypeBean;
import com.wsc.wisdomchinaqinghe.javaBean.RespObj;
import com.wsc.wisdomchinaqinghe.presenter.ContributorPresenter;
import com.wsc.wisdomchinaqinghe.view.MyGridView;
import com.wsc.wisdomchinaqinghe.view.MyToast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 楼宇发布页面
 * Created by ${wangtao} on 2017/3/6.
 */

public class PeopleControlPublishActivity extends BaseActivity implements View.OnClickListener,ContributorView {

    private Context context;
    private int imageFlag = 1;
    private Bitmap photo;
    private ContributorPresenter contributorPresenter;
    private final String UPLOADPICTUREFLAG="UPLOADPICTUREFLAG";
    private String resultParam="";
    private String uid;
    private MyToast myToast;
    private String cidRequest;
    private String uidRequest;
    private String typeRequest;
    private String release_nameRequest;
    private String titleRequest;
    private String addrRequest;
    private String contentRequest;
    private String imgRequest;
    private final String RELEASEBUILDINGFLAG="RELEASEBUILDINGFLAG";

    private final String  FEEDBACKTYPEFLAG="FEEDBACKTYPEFLAG";
    private ImageView fragment_bxjdfb_back;//返回
    private EditText fragment_bxjdfb_name;//報案人姓名
    private EditText fragment_bxjdfb_address;
    private EditText fragment_bxjdfb_title;
    private EditText fragment_bxjdfb_content;
    private ImageView one_one, one_two, one_three;
    private Button fragment_bxjdfb_enter;
    private TextView tv_cancelPhone;
    private TextView tv_takephoto;
    private TextView tv_photo;
    private PopupWindow popupWindowPhone;
    private View mpopupWindowViewPhone;
    private List<String> nameList;
    private TextView tv_headtitle;
    private MyGridView gridview;
    private String cidNumber;
    private PeopleControlTypeAdapter peopleControlTypeAdapter;
    private String type="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.peoplecontrolpublish_layout);
        context = this;
        myToast=new MyToast(context);
        cidNumber=getIntent().getStringExtra("cid");
        uid=Tools.getSharedPreferencesStrings(Constant.SharePreferenceUserid,"",context);
        myToast=new MyToast(context);
        contributorPresenter=new ContributorPresenter(this,context);
        initView();
        initPopupWindowPhone();
        contributorPresenter.getFeedBackType(cidNumber,FEEDBACKTYPEFLAG);
    }


    private void initView() {
        fragment_bxjdfb_back= (ImageView) findViewById(R.id.regist_back);//返回
        fragment_bxjdfb_name= (EditText) findViewById(R.id.fragment_bxjdfb_name);//報案人姓名
        fragment_bxjdfb_address= (EditText) findViewById(R.id.fragment_bxjdfb_address);
        fragment_bxjdfb_title= (EditText) findViewById(R.id.fragment_bxjdfb_title);
        fragment_bxjdfb_content= (EditText) findViewById(R.id.fragment_bxjdfb_content);
        fragment_bxjdfb_enter= (Button) findViewById(R.id.fragment_bxjdfb_enter);
        tv_headtitle=(TextView) findViewById(R.id.tv_headtitle);
        tv_headtitle.setText("发布");

        tv_headtitle.requestFocus();
        tv_headtitle.setFocusable(true);
        tv_headtitle.setFocusableInTouchMode(true);

        one_one = (ImageView) findViewById(R.id.one_one);
        one_two = (ImageView) findViewById(R.id.one_two);
        one_three = (ImageView) findViewById(R.id.one_three);

        one_one.setOnClickListener(this);
        one_two.setOnClickListener(this);
        one_three.setOnClickListener(this);
        fragment_bxjdfb_back.setOnClickListener(this);
        fragment_bxjdfb_enter.setOnClickListener(this);
        gridview=(MyGridView) findViewById(R.id.gridview);
        gridview.setHaveScrollbar(false);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                peopleControlTypeAdapter.setPosition(position);
                peopleControlTypeAdapter.notifyDataSetChanged();
                type=nameList.get(position);
            }
        });

    }

    /**
     * @param v 处理点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_bxjdfb_enter:
                charge_Data(cidNumber,uid,type, fragment_bxjdfb_name.getText().toString(),
                        fragment_bxjdfb_title.getText().toString(),fragment_bxjdfb_address.getText().toString(),fragment_bxjdfb_content.getText().toString()
                        ,resultParam);
                break;
            case R.id.one_one:
                imageFlag = 1;
                View view = getWindow().peekDecorView();
                if (view != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.one_one), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            case R.id.one_two:
                imageFlag = 2;
                View view1 = getWindow().peekDecorView();
                if (view1 != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view1.getWindowToken(), 0);
                }
                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.one_one), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            case R.id.one_three:
                imageFlag = 3;
                View view2 = getWindow().peekDecorView();
                if (view2 != null) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view2.getWindowToken(), 0);
                }

                if (!popupWindowPhone.isShowing()) {
                    popupWindowPhone.showAtLocation(findViewById(R.id.one_one), Gravity.BOTTOM, 0, 0);// 在屏幕居中，无偏移
                } else {
                    popupWindowPhone.dismiss();
                }
                break;
            case R.id.regist_back:
                finish();
                break;
            // 取消点击事件
            case R.id.tv_cancel:
                popupWindowPhone.dismiss();
                break;
            // 拍照点击事件
            case R.id.tv_takephoto:
                popupWindowPhone.dismiss();
                try {
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                            }
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {

                                    Uri uri = getUri();
                                    Intent intent = new Intent();
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//将拍取的照片保存到指定URI
                                    startActivityForResult(intent,6);
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });
                }catch (Exception e)
                {
                    myToast.showShort("拍照失败");
                }

                break;
            // 用户相册点击事件
            case R.id.tv_photo:
                popupWindowPhone.dismiss();
                try{
                    AbPermissionUtils.requestPermissionsResult(this, 1
                            , new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                            }
                            , new AbPermissionUtils.OnPermissionListener() {
                                @Override
                                public void onPermissionGranted() {
                                    Intent intentphoto = new Intent(Intent.ACTION_PICK, null);
                                    intentphoto.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                    startActivityForResult(intentphoto, 1);
                                }

                                @Override
                                public void onPermissionDenied() {

                                }
                            });
                }catch (Exception e)
                {
                    myToast.showShort("读取相册失败");
                }
                break;
        }
    }


    /**
     * 初始化popupwindow
     */
    private void initPopupWindowPhone() {
        mpopupWindowViewPhone = LayoutInflater.from(getApplicationContext()).inflate(R.layout.headinfo, null);
        popupWindowPhone = new PopupWindow(mpopupWindowViewPhone, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);// 全屏显示，将内容设置在底部
        popupWindowPhone.setFocusable(true);
        popupWindowPhone.setBackgroundDrawable(new BitmapDrawable());

        tv_cancelPhone = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_cancel);
        tv_cancelPhone.setOnClickListener(this);
        tv_takephoto = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_takephoto);
        tv_takephoto.setOnClickListener(this);
        tv_photo = (TextView) mpopupWindowViewPhone.findViewById(R.id.tv_photo);
        tv_photo.setOnClickListener(this);
    }

    @Override
    public void onLoadContributorStart(String flag) {
        if(flag.equals(RELEASEBUILDINGFLAG))
        {
            fragment_bxjdfb_enter.setEnabled(false);
        }

    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
//        Log.e("http",flag+":"+jsonString);
        try {
            if(flag.equals(FEEDBACKTYPEFLAG))
            {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object message=respObj.getMessage();
                if (code.equals("200") && message!=null) {
                    String jsonMessage=JsonTools.objectToJsonString(message);
                    List<FeedBackTypeBean> list=JsonTools.jsonStringToList(jsonMessage,FeedBackTypeBean.class);
                    nameList=new ArrayList<>();
                    if(list.size()>0)
                    {
                        for(FeedBackTypeBean feedBackTypeBean:list)
                        {
                            nameList.add(feedBackTypeBean.getName());
                        }
                    }
                    if(nameList!=null && nameList.size()>0)
                    {
                        peopleControlTypeAdapter=new PeopleControlTypeAdapter(context,nameList);
                        gridview.setAdapter(peopleControlTypeAdapter);
                    }

                }
            }
            if (flag.equals(UPLOADPICTUREFLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object message=respObj.getMessage();
                if (code.equals("200") && message!=null) {
                    String jsonMessage=JsonTools.objectToJsonString(message);
                    List<String> list=JsonTools.jsonStringToList(jsonMessage,String.class);
                    if(list!=null && list.size()>0)
                    {
                        String picRequest="";
                        for(String pic:list)
                        {
                            picRequest+=pic;
                            picRequest+=",";
                        }
                        contributorPresenter.getFeedbackSubmit(cidRequest,uidRequest,typeRequest,release_nameRequest,titleRequest,addrRequest,contentRequest,picRequest,RELEASEBUILDINGFLAG);
                    }
                } else {
                    myToast.showShort("上传图片失败");
                }
            }else if(flag.equals(RELEASEBUILDINGFLAG))
            {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object message=respObj.getMessage();
                if (code.equals("200") && message!=null) {
                    myToast.showShort("发布成功");
                    Intent intent=getIntent();
                    setResult(1,intent);
                    finish();
                }else
                {
                    myToast.showShort("操作失败");
                }
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
        if(flag.equals(RELEASEBUILDINGFLAG))
        {
            fragment_bxjdfb_enter.setEnabled(true);
        }

    }

    @Override
    public void onLoadContributorError(String error, String flag) {

    }




    private void charge_Data(String cid,String uid,String type,String release_name, String title,String addr,String content,String img) {
        if(type.isEmpty() || release_name.isEmpty() || title.isEmpty() || addr.isEmpty() || content.isEmpty() ||
                img.isEmpty())
        {
            myToast.showShort("请填写完整信息");
        }else
        {
            contributorPresenter.getUploadCommonPicList(img,UPLOADPICTUREFLAG);
            cidRequest=cid;
            uidRequest=uid;
            typeRequest=type;
            release_nameRequest=release_name;
            titleRequest=title;
            addrRequest=addr;
            contentRequest=content;
            imgRequest=img;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 从相册里面获取
            case 1:
                if (data != null && data.getData() != null) {
                    startPhotoZoom(data.getData());
                }
                break;
            // 裁剪
            case 2:
                if (data != null) {
                    setPicToView(data);
                }
                break;
            // 拍照
            case 6:
                startPhotoZoomCut();
                break;
        }
    }

    private Uri getUri() {
        try{
            File cacheDir;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                cacheDir = new File(Environment.getExternalStorageDirectory(), Constant.wsc_photo);
            else
                cacheDir = context.getCacheDir();
            if (!cacheDir.exists())
                cacheDir.mkdirs();

            File path = new File(cacheDir, "");
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(path, "peoplecontrol.jpg");
            //由于一些Android 7.0以下版本的手机在剪裁保存到URI会有问题，所以根据版本处理下兼容性
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return FileProvider.getUriForFile(context, "com.wsc.wisdomchinaqinghe.fileprovider", file);
            } else {
                return Uri.fromFile(file);
            }
        }catch (Exception e)
        {
            return null;
        }

    }


    /**
     * @param uri
     * @Description 裁剪图片从相册
     * @author jaily.zhang
     */
    private void startPhotoZoom(Uri uri) {
        try {
                 /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能, 是直接调本地库的，小马不懂C C++
		 * 这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么 制做的了...吼吼
		 */
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 0.8);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("return-data", true);
            startActivityForResult(intent, 2);
        } catch (Exception e) {

        }
    }
    /**
     * 裁剪图片从拍照
     */
    private void startPhotoZoomCut()
    {
        try {
            Uri uri = getUri();
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            intent.setDataAndType(uri , "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 0.8);
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, getUri());
            intent.putExtra("return-data", true);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("noFaceDetection", true);

            //将存储图片的uri读写权限授权给剪裁工具应用
            List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            startActivityForResult(Intent.createChooser(intent, "选择剪裁工具"), 2);
        } catch (Exception e) {

        }
    }
    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            photo = extras.getParcelable("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            if (photo != null) {
                try {
                    // Drawable drawable = new BitmapDrawable(photo);

                    /**
                     * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似
                     */

                    int options = 70;
                    photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                    byte[] b = stream.toByteArray();// 将图片流以字符串形式存储下来
                    // 大于2KB
                    while (b.length > 5 * 1024) {
                        stream.reset();// 清空流
                        options -= 10;
                        photo.compress(Bitmap.CompressFormat.JPEG, options, stream);
                        b = stream.toByteArray();
                    }

                    Message message=new Message();
                    message.what=imageFlag;
                    mHandler.sendMessage(message);

                } catch (Exception e) {

                } finally {
                    try {
                        // 关闭流
                        stream.flush();
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }

    // handler 消息处理
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Drawable drawable = new BitmapDrawable(photo);
                    one_one.setImageDrawable(drawable);
                    one_two.setVisibility(View.VISIBLE);
                    resultParam= BitmapUtils.bitmapToBase64(photo);
                    break;
                case 2:
                    Drawable drawable2 = new BitmapDrawable(photo);
                    one_two.setImageDrawable(drawable2);
                    one_three.setVisibility(View.VISIBLE);
                    resultParam+=",";
                    resultParam+= BitmapUtils.bitmapToBase64(photo);
                    break;
                case 3:
                    Drawable drawable3 = new BitmapDrawable(photo);
                    one_three.setImageDrawable(drawable3);
                    resultParam+=",";
                    resultParam+= BitmapUtils.bitmapToBase64(photo);
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(photo!=null && !photo.isRecycled())
        {
            photo.isRecycled();
            photo=null;
        }
    }

}
